package com.gyul.findmystock.analysis;



public class MACD {
	private final String TAG ="MACD";
	
	int [] close;
	public float [] macd;
	public float [] signal;
	public float [] osc;
	
	int shortMA;
	int longMA;
	int macdMA;
	public int startIndex = 0;
	
	public MACD(int [] close) {
		this(close, 9, 12, 26);	
	}
	
	public MACD(int [] close, int shortMA, int longMA, int macdMA) {
		this.close = close;
		
		macd = new float [close.length];
		signal = new float [close.length];
		osc = new float [close.length];
				
		setDay(shortMA, longMA, macdMA);		
	}
	
	public void setDay(int shortMA, int longMA, int macdMA) {
		this.shortMA = shortMA;
		this.longMA = longMA;
		this.macdMA = macdMA;	
		this.startIndex = Math.max(macdMA, Math.max(shortMA, longMA));
	}
	
	public void calculate() {
		
	}
	
	public void computeMacd() {
		float [] shortLine = computeEMA(shortMA);
		float [] longLine = computeEMA(longMA);
		float [] macdLine;
		
		for ( int i = 0; i < close.length; i++ ) {
			if ( i < startIndex ) {
				macd[i] = 0;
			} else {			
				macd[i] = shortLine[i] - longLine[i];
			}
		}	
		
		macdLine = computeMacdEMA(macdMA);
		
		
		for ( int i = 0; i < close.length; i++ ) {
			if ( i < startIndex ) {
				signal[i] = osc[i] = 0;
			} else {			
				signal[i] = macdLine[i];			
				osc[i] = Float.parseFloat(String.format("%.2f", macd[i] - signal[i]));
			}
		}		
	}
	
	/*
	 * EMA = Price(t) * k + MA(y) * (1 - k)
	 * t = today, y = yesterday, N = number of days in EMA, k = 2/(N+1)
	 * if MA(y) == 0, close[t]
	 */	
	public float [] computeEMA(int day) {
		float k = 2.0f / ( day + 1.0f ); 
		float [] ema = new float [close.length];
		float sumClose = 0;		
		
		for ( int i = 0; i < day; i++ ) {
			ema[i] = 0;
			sumClose += close[i];
		}
		
		ema[day-1] = sumClose / day;
		
		for ( int i = day; i < close.length; i++ ) {
			ema[i] = (k * (close[i] - ema[i-1])) + ema[i-1];
		}
		
		return ema;
	}
	
	public float [] computeMacdEMA(int day) {
		float k = 2.0f / ( day + 1.0f ); 
		float [] ema = new float [macd.length];
		float sumMacd = 0;		
		
		for ( int i = 0; i < day; i++ ) {
			ema[i] = 0;
			sumMacd += macd[i];
		}
		
		ema[day-1] = sumMacd / day;
		
		for ( int i = day; i < macd.length; i++ ) {			
			ema[i] = (k * (macd[i] - ema[i-1])) + ema[i-1];			
		}
		
		return ema;
	}
}
